const shell=require('shelljs')
const path=require('path')
const fs= require('fs')
const iconv = require('iconv-lite')
const cliPath='E:/programefiles/HBuilderX/cli.exe'
const project="yfs-cw"
let desc="测试"
let version="2.2.81"
const wxs=[
	{
		appid:'wxed24403b6df66422',
		name:'潮玩一番赏',
		key:'isYfs',
		upload:true
	},
	{
		appid:'wx6471aa748d285110',
		name:'潮玩Play',
		key:'isPlay',
		upload:true
	},
	{
		appid:'wx29e31a0755cc2356',
		name:'潮玩社区',
		key:'isCommunity',
		upload:true
	},
	{
		appid:'wx9b0090b01185a3c2',
		name:'潮玩joy',
		key:'isJoy',
		upload:true
	},
	{
		appid:'wx0f6386e486d9ef6d',
		key:'isDigital',
		upload:false
	}
]
//shell.exec(`chcp 65001`)
if(!shell.which(cliPath)){
  shell.echo('Sorry, this script requires HBuilderX->cli.exe');
  shell.exit(1);
}

const configPath = path.resolve(__dirname,'../vue.config.js')
let config = fs.readFileSync(configPath, { encoding: 'utf-8' })
const wxArr=wxs.filter(item => item.upload)
wxArr.map((item,idx) =>{
	wxs.map(item1 =>{
		config=config.replace(new RegExp(`${item1.key}=(?:true|false)`),`${item1.key}=false`)
	})
	config=config.replace(new RegExp(`${item.key}=(?:true|false)`),`${item.key}=true`)
	fs.writeFileSync(configPath,config, {
	  "flag": "w"
	})
	const privatekey=path.resolve(__dirname,`./certs/private.${item.appid}.key`)
	//console.log(privatekey)
	uploadWx(item.appid,privatekey,item.name)
})
function uploadWx(appid,privatekey,name){
	const cliExec = shell.exec(
		`${cliPath} publish --platform mp-weixin --project ${project} --upload true --appid ${appid} --description ${desc} --version ${version} --privatekey ${privatekey}`,
		{async:false,encoding:'buffer',silent:true},
	)
	const err=iconv.decode(cliExec.stderr, 'gb2312')
	const out=iconv.decode(cliExec.stdout, 'gb2312')
	if(out.indexOf('上传项目到微信平台成功')!=-1){
		console.log(`========================================`)
		console.log(`小程序名称: ${name}`)
		console.log(`版本号: ${version}`)
		console.log(`项目备注: ${desc}`)
		console.log(`appId: ${appid}`)
		console.log(`========================================`)
	}else{
		console.error(out);
	}
}
